package ks.app.smartDic;

import java.util.List;

import net.daum.mobilead.MobileAdView;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.ImageView;
import android.widget.Toast;

public class SearchView extends Activity implements OnClickListener {

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	PackageManager pm;

	AutoCompleteTextForNaverDic editTextSearchName;
	ImageView btnVoiceSearch;
	ImageView btnSearch;

	String sortOfDictionary;

	//AdView adView;
	//RelativeLayout layout;
	MobileAdView adViewAdam;
	MultipleAd mAd;

	GoogleAnalyticsTracker tracker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		Intent LastIntent = getIntent();
		sortOfDictionary = LastIntent
				.getStringExtra(getString(R.string.SORT_OF_DICTIONARY));

		if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_KOREAN)) == 0) {

			setContentView(R.layout.engtokor);
			//layout = (RelativeLayout) findViewById(R.id.layoutEngToKor);

		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_ENG)) == 0) {

			setContentView(R.layout.kortoeng);
			//layout = (RelativeLayout) findViewById(R.id.layoutKorToEng);

		}

		else if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_ENG)) == 0) {

			setContentView(R.layout.engtoeng);
			//layout = (RelativeLayout) findViewById(R.id.layoutEngToEng);

		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0) {

			setContentView(R.layout.search);
			//layout = (RelativeLayout) findViewById(R.id.layoutKorToKor);

		}

		if (HasVoiceRecognition()) {

			btnVoiceSearch = (ImageView) findViewById(R.id.btnVoiceSearch);
			btnVoiceSearch.setOnClickListener(this);

		} else {

			ksLog.d("no voice recognition");

		}

		btnSearch = (ImageView) findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(this);

		editTextSearchName = (AutoCompleteTextForNaverDic) findViewById(R.id.editTextSearchName);
		editTextSearchName
				.setURL("http://ac.endic.naver.com/ac?_callback=&q_enc=utf-8&st=1100&r_format=json&r_enc=utf-8&r_lt=1000&r_unicode=0&r_escape=1&q=");
		editTextSearchName.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& keyCode == KeyEvent.KEYCODE_ENTER) {

					goSearch();

				}
				return false;
			}
		});

		
		  adViewAdam = (MobileAdView) findViewById(R.id.adviewAdam);
		  
		  mAd = new MultipleAd(getApplicationContext(), adViewAdam);
		  mAd.displayAd();

/*
		adView = new AdView(this, AdSize.BANNER,
				getString(R.string.ADMOB_PUBLISHER_ID));

		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
				RelativeLayout.TRUE);
		layout.addView(adView, layoutParams);
		adView.loadAd(new AdRequest());
		*/

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start("UA-22873894-1", 20, this);
		tracker.trackPageView("/search");
		tracker.dispatch();

	}

	private void goSearch() {

		if (editTextSearchName.getText().length() == 0) {
			Toast.makeText(getApplicationContext(), "검색어를 입력해 주세요.",
					Toast.LENGTH_SHORT).show();
			return;
		}

		SharedPreferences sp;
		String[] listName = getResources().getStringArray(
				R.array.entries_list_preference);
		sp = getSharedPreferences("PrefSmartDic", 0);
		String targetClassName = sp.getString(
				getString(R.string.PREF_RESULT_VIEW), listName[1]);

		Intent goSearch;
		if (targetClassName.compareTo(listName[0]) == 0)
			goSearch = new Intent(getApplicationContext(), TabOriginal.class);
		else
			goSearch = new Intent(getApplicationContext(), tabView.class);

		goSearch.putExtra(getString(R.string.SORT_OF_DICTIONARY),
				sortOfDictionary);
		goSearch.putExtra("query", editTextSearchName.getText().toString());

		editTextSearchName.setText(null);

		startActivity(goSearch);
	}

	public void onClick(View v) {

		if (v == btnVoiceSearch) {

			startVoiceRecognitionActivity();

		} else if (v == btnSearch) {

			goSearch();

		}
	}

	private Boolean HasVoiceRecognition() {

		pm = getPackageManager();

		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);

		if (activities.size() != 0) {

			return true;

		} else {

			return false;

		}
	}

	private void startVoiceRecognitionActivity() {

		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

		if (sortOfDictionary.compareTo(getString(R.string.KOREAN_TO_ENG)) == 0
				|| sortOfDictionary
						.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0) {

			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko");
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "한단어를 말씀해 주십시오.");

		} else {

			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
					"Please speak an English Word.");

		}

		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
				&& resultCode == RESULT_OK) {

			Intent intent = new Intent(getApplicationContext(),
					ResultView.class);
			intent.putStringArrayListExtra("data", data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
			intent.putExtra(getString(R.string.SORT_OF_DICTIONARY),
					sortOfDictionary);

			startActivity(intent);

		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	protected void onResume() {

		super.onResume();

		mAd.displayAd();

	}
}
